package com.dingpeikeji.quickdeer.modules.wx.rentprocut.web;

import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.DemandsReact;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ProRentOrders;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TDemands;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FDemandsService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.modules.wx.common.web.OAuth;
import com.google.common.collect.Lists;

/**
 * 用户需求Controller
 */
@Controller
@RequestMapping("wx/pu/demands")
public class WxDemandsController extends BaseController{
	@Autowired
	private FDemandsService demandsService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private TCargotypeService tCargotypeService;
	@Autowired
	private FRentproductService rentproductService;
	
	@RequestMapping("list")
	public String list(TDemands tDemands, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = (User) request.getSession().getAttribute(OAuth.SESSION_PUBUSER);
		tDemands.setCreateBy(user);
		Page<TDemands> page = demandsService.findPage(new Page<TDemands>(request, response), tDemands); 
		model.addAttribute("page", page);
		model.addAttribute("tDemands", tDemands);
		
		// 如果是查看历史，则调到历史页面
		
		if(StringUtils.isNotBlank(tDemands.getHistory()) && tDemands.getHistory().equals("yes")){
			return "wx/modules/demands/demandsHistory";
		} else {
			return "wx/modules/demands/demandsList";
		}
	}

	@RequestMapping(value = "form",method=RequestMethod.GET)
	public String form(TDemands tDemands, Model model) {
		String demandid = tDemands.getDemandid()==null?null:(""+tDemands.getDemandid());
		if (demandid != null){
			tDemands = demandsService.get(""+tDemands.getDemandid());
			if(!tDemands.getReactstatus().equals(TDemands.REACTSTATUS_CANCEL) && !tDemands.getReactstatus().equals(TDemands.REACTSTATUS_DONE)) {
				model.addAttribute("reactList", demandsService.findDemandsReactList(tDemands));
			}
		}
		
		// 如果起止时间都为空，则设置默认起止时间
		if(tDemands.getFromdate() == null) {
			// 租赁开始日期默认第二天及结束日期（默认一年）
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DAY_OF_MONTH, 1);
			calendar.set(Calendar.HOUR_OF_DAY, 9);
			calendar.set(Calendar.MINUTE, 0);
			tDemands.setFromdate(calendar.getTime());
		}
		
		// 车型数据
		List<TCargotype> cargotypeList = tCargotypeService.findList(new TCargotype());
		model.addAttribute("cargotypeList", cargotypeList);
		model.addAttribute("tDemands", tDemands);
		return "wx/modules/demands/demandsForm";
	}
	
	@RequestMapping(value = "view")
	public String view(TDemands tDemands, Model model) {
		String history = tDemands.getHistory();
		tDemands = demandsService.get(""+tDemands.getDemandid());
		if(!tDemands.getReactstatus().equals(TDemands.REACTSTATUS_CANCEL) && !tDemands.getReactstatus().equals(TDemands.REACTSTATUS_DONE)) {
			model.addAttribute("reactList", demandsService.findDemandsReactList(tDemands));
		}
		tDemands.setHistory(history);
		model.addAttribute("tDemands", tDemands);
		return "wx/modules/demands/demandsView";
	}

	@RequestMapping(value = "form",method=RequestMethod.POST)
	public String save(TDemands tDemands, Model model,HttpServletRequest request, RedirectAttributes redirectAttributes) {
		List<String> messages = Lists.newArrayList();
		if(tDemands.getDepartcity()==null || ValidateTool.isEmptyOrNull(tDemands.getDepartcity().getSiteid())) {
			messages.add("出发地不能为空!");
		}
		if(tDemands.getDestcity()==null || ValidateTool.isEmptyOrNull(tDemands.getDestcity().getSiteid())) {
			messages.add("目的地不能为空!");
		}
		if(tDemands.getCartype()==null || tDemands.getCartype().getCargotypeid() == null) {
			messages.add("车型不能为空!");
		}
		if(tDemands.getVehiclenum() == null){
			messages.add("包车数量不能为空!");
		}
		if(StringUtils.isBlank(tDemands.getFromdateStr()) && StringUtils.isBlank(tDemands.getTime())){
			messages.add("用车时间不能为空!");
		} else {
			try {
				tDemands.setFromdate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(tDemands.getFromdateStr()+" " +tDemands.getTime()+":00"));
			} catch (ParseException e) {
				messages.add("用车时间格式不对!");
			}
		}
		if(tDemands.getRentdays() == null){
			messages.add("包车天数不能为空!");
		}
		if(ValidateTool.isEmptyOrNull(tDemands.getContactor())){
			messages.add("联系人不能为空!");
		}
		String phone = tDemands.getContactphone();
		if(!ValidateTool.isMobile(phone) &&
				!ValidateTool.isPhone(phone)) {
			messages.add("联系人电话不正确!");
		}
		tDemands.setReactstatus(TDemands.REACTSTATUS_WAIT);
		if(tDemands.getDemandid()==null){
			User user = (User) request.getSession().getAttribute(OAuth.SESSION_PUBUSER);
			tDemands.setCreateBy(user);
			tDemands.setCreateDate(new Date());
		}
		if(messages.isEmpty()) {
			tDemands.setSeats(tDemands.getCartype().getSeats());
			demandsService.save(tDemands);
			addMessage(redirectAttributes, "正在对您的需求进行报价，请耐心等候，为保证您的顺利用车，获得报价响应后请尽快确认支付。");
			return "redirect:/wx/pu/demands/list?reactstatus="+TDemands.REACTSTATUS_WAIT+"&repage";
		} else {
			addMessage(model, messages.toArray(new String[]{}));
			return form(tDemands, model);
		}
	}
	
	@RequestMapping(value = "cancel")
	public String cancel(TDemands tDemands, RedirectAttributes redirectAttributes) {
		tDemands= this.demandsService.get(""+tDemands.getDemandid());
		String status = tDemands.getReactstatus();
		tDemands.setReactstatus(TDemands.REACTSTATUS_CANCEL);
		demandsService.save(tDemands);
		addMessage(redirectAttributes, "取消用车需求成功");
		return "redirect:/wx/pu/demands/list?reactstatus="+status+"&repage";
	}
	
	@RequestMapping(value = "book")
	public String book(TDemands tDemands,Integer reactid, Model model) {
		DemandsReact react = demandsService.getDemandsReact(reactid);
		tDemands = demandsService.get(""+tDemands.getDemandid());
		model.addAttribute("tDemands", tDemands);
		model.addAttribute("react", react);
		return "wx/modules/demands/demandsBook";
	}
	
	@RequestMapping("booking")
	public String booking(String reactid,String demandid, TOrders orders,Model model,RedirectAttributes redirectAttributes, HttpServletRequest request) throws ParseException{
		String redirctPage = "redirect:/wx/pu/demands/book?demandid={0}&reactid={1}"; // 订单信息页
		String payWayPage = "redirect:/wx/pay/payWay?orderid={0}"; // 支付方式选择页
		
		User user = null;
		user = (User) request.getSession().getAttribute(OAuth.SESSION_PUBUSER);
		orders.setOrderuserid(user.getId());

		// 校验数据
		
		// 消息集合
		List<String> messages = Lists.newArrayList(); // 消息
		if(ValidateTool.isEmptyOrNull(orders.getPurchasenum())){
			messages.add("请填写车辆数");
		} else if (!ValidateTool.isNonnegativeDigit(orders.getPurchasenum())) {
			messages.add("车辆数量不正确");
		}
		if(ValidateTool.isEmptyOrNull(orders.getBoardaddr())){
			messages.add("请填写上车地点");
		}
		if(ValidateTool.isEmptyOrNull(orders.getContacts())){
			messages.add("请填写联系人姓名");
		}
		if(ValidateTool.isEmptyOrNull(orders.getOrdertype())){
			messages.add("未知用途的订单");
		}
		if(ValidateTool.isEmptyOrNull(orders.getPayertel())){
			messages.add("请填写联系电话");
		} else if(!ValidateTool.isMobile(orders.getPayertel())) {
			messages.add("电话号码不正确");
		}
		
		DemandsReact react = demandsService.getDemandsReact(Integer.parseInt(reactid));
		if(messages.isEmpty()) {
			TDemands demand = demandsService.get(react.getDemandid()+"");
			if(!TDemands.REACTSTATUS_SURE.equals(demand.getReactstatus())) {
				messages.add("该定制需求不可支付");
			}
		}
		
		if(messages.isEmpty()) {
			
			orders.setDueamount(""+react.getPrice());
			ProRentOrders pro = null;

			try {
				pro = rentproductOrderService.genOrder(orders);
				if(pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					return MessageFormat.format(payWayPage, orderid.toString());
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		redirectAttributes.addFlashAttribute("orders", orders);
		addMessage(redirectAttributes, messages.toArray(new String[]{}));
		return MessageFormat.format(redirctPage, demandid, reactid);
	}
}
